# -*- coding:utf-8 -*-
import json

# @Time    : 2023/5/16 02:21
# @Author  : zengwenjia
# @Email   : zengwenjia@lingxi.ai
# @File    : generate_bot_dialogue.py
# @Software: LLM_internal

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
import pandas as pd
import asyncio
from bot.insurance_sales_huize.sales import Sales
# from bot.insurance_sales_huize.user import User
import uuid
from data_generate import utils
import traceback
import random
from loguru import logger


def conversation2csv(file_path):
    datas = utils.jload(file_path)
    df = pd.DataFrame(columns=['角色', '内容'])

    for data in datas:
        messages = data['messages']
        for text in messages:
            df = df._append(
                {"角色": text['role'],
                 "内容": text['content']},
                ignore_index=True)
        df = df.reset_index(drop=True)._append(
            {"角色": "",
             "内容": ""},
            ignore_index=True)
    df.to_csv(file_path.replace('.json', '.csv'))


if __name__ == '__main__':
    import datetime
    # df=pd.read_excel("慧择对话文本-format.xlsx")
    df=pd.read_excel("投诉case-format.xlsx")
    for session_id in df.session_id.unique()[:100]:
        sales = Sales()
        user_df=df[df.session_id==session_id].reset_index(drop=True)
        for record in user_df.to_records():
            if record['index']==0:
                conversation_dict = {}
                conversation_dict["role"] = "assistant"
                conversation_dict["content"] = record['过滤文本']
                conversation_history=[conversation_dict]
            else:
                conversation_dict = {}
                conversation_dict["role"] ="user" if record['speaker_type']=="USER" else "assistant"
                conversation_dict["content"] = record['过滤文本']
                conversation_history.append(conversation_dict)

                if conversation_dict["role"] =="user":
                    result = asyncio.run(sales.async_reply_web(conversation_history, session_id, content=conversation_dict["content"],is_need_format=1))
                    logger.info('历史对话缓存:{}'.format(conversation_history))
                    if '再见' in result or '马上为您服务' in result:
                        logger.info("*******对话已经结束：转人/挂机*******\n\n\n")
                        conversation_history = []
                        user_input = ''


